﻿using MB.Orm.DB;
using MB.RuleBase.Common;
using Model;
using Public.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Business.Service
{
    public class BDCInventory
    {
        public BDCInventory() { }
        /// <summary>
        /// 获取前置仓仓库库存信息
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="total"></param>
        /// <param name="parValues"></param>
        /// <returns></returns>
        public List<DCInventory> GetDCInventoryInfo(int pageIndex, int pageSize, out int total, params object[] parValues)
        {
            using (var DbScope = new OperationDatabaseScope(new OperationDatabaseContext("NewWeb")))
            {
                List<DCInventory> list = PagedDatabaseExcuteByXmlHelper.NewInstance.GetPagedObjectsByXml3<DCInventory>
                                                ("DCDBA", "GetDCInventoryInfo", pageIndex, pageSize, out total, parValues);
                return list;
            }
        }


        /// <summary>
        /// 获取前置仓库存转仓信息
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="total"></param>
        /// <param name="parValues"></param>
        /// <returns></returns>
        public List<DCInventoryMove> GetDCInventoryMove(int pageIndex, int pageSize, out int total, params object[] parValues)
        {
            using (var DbScope = new OperationDatabaseScope(new OperationDatabaseContext("NewWeb")))
            {
                List<DCInventoryMove> list = PagedDatabaseExcuteByXmlHelper.NewInstance.GetPagedObjectsByXml3<DCInventoryMove>
                                                ("DCDBA", "GetDCInventoryMove", pageIndex, pageSize, out total, parValues);
                return list;
            }
        }

        public bool UploadDCInventory(string userCode, string goodsCode, out string mes)
        {
            mes = string.Empty;
            bool result = true;
            List<DCInventory> lstDCInventory = GetDCInventoryUploadInfo(userCode, goodsCode);
            List<JDGoodsInfo> lstJDGoodsInfo = GetJDGoods();
            var p = from a in lstDCInventory
                    join b in lstJDGoodsInfo on a.GOODSCODE equals b.outSkuId
                    select new
                    {
                        a.ID,
                        a.GOODSCODE,
                        b.skuId,
                        //USEFULQTY = a.USEFULQTY,
                        USEFULQTY = a.ACTUALQTY - a.FROZENQTY - a.WARNINGMSG > 0 ?
                        (int)a.INVENTORYPROPORTION * (a.ACTUALQTY - a.FROZENQTY - a.WARNINGMSG) :
                        (int)a.INVENTORYPROPORTION * (a.ACTUALQTY - a.FROZENQTY),
                        a.THIRDSTORECODE
                    };
            if (p.Count() <= 0)
            {
                result = false;
                mes = "没有需要推送库存的商品！";
            }
            //List<DCInventory> lstDCInventoryUpdate = new List<DCInventory>();
            foreach (var item in p)
            {
                result = result && UploadJDcurruntQty(item.skuId, item.USEFULQTY, item.THIRDSTORECODE, out mes);
                result = result && UpdateDCInventoryUseful(item.ID, item.USEFULQTY);
                //上传饿了么可用库存
                //DCInventory _DCInventory = new DCInventory();
                //_DCInventory.GOODSCODE = item.GOODSCODE;
                //_DCInventory.USEFULQTY = item.USEFULQTY;
                //lstDCInventoryUpdate.Add(_DCInventory);
            }
            //JObject jsonObj = new JObject();
            //result = result && new ElemeRepository().UpdateStockByTp_FoodId("", lstDCInventoryUpdate, out jsonObj);
            return result;
        }

        public bool UpdateDCInventoryUseful(int ID, int USEFULQTY)
        {
            try
            {
                return DatabaseExcuteByXmlHelper.NewInstance.ExecuteNonQuery("DCDBA", "UpdateDCInventoryUseful", ID, USEFULQTY) > 0;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return false;
            }
        }

        public bool UpdateDCInventoryUseful(List<DCInventory> lstDCInventory)
        {
            try
            {
                if (lstDCInventory == null || lstDCInventory.Count <= 0) return true;

                using (MB.RuleBase.BulkCopy.IDbBulkExecute bulk = MB.RuleBase.BulkCopy.DbBulkExecuteFactory.CreateDbBulkExecute())
                {
                    bulk.WriteToServer("DCDBA", "UpdateDCInventoryUseful", lstDCInventory);
                    return true;
                }
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return false;
            }
        }

        public List<DCInventory> GetDCInventoryUploadInfo(string userCode, string goodsCode)
        {
            using (var DbScope = new OperationDatabaseScope(new OperationDatabaseContext("NewWeb")))
            {
                List<DCInventory> list = DatabaseExcuteByXmlHelper.NewInstance.GetObjectsByXml<DCInventory>("DCDBA", "GetDCInventoryUploadInfo"
                       , userCode, goodsCode);
                return list;
            }
        }

        public bool UploadJDcurruntQty(long skuId, int usefulQty, string ThirdStoreCode, out string mes)
        {
            mes = string.Empty;
            bool success = true;
            List<JDGoodsInfo> lstJDGoodsInfo = new List<JDGoodsInfo>();
            try
            {
                request_upload _request = new request_upload();
                _request.skuId = skuId.ToString();
                _request.currentQty = usefulQty.ToString();
                _request.stationNo = ThirdStoreCode;
                string action = "/update/currentQty";
                string jd_param_json = JsonConvert.SerializeObject(_request);
                string response = GetJDAPI(action, jd_param_json);
                JObject responseJObject = JObject.Parse(response);
                success = (bool)responseJObject["success"];
                bool isRet = true;
                if (success)
                {
                    string data = responseJObject["data"].ToString();
                    JObject dataJObject = JObject.Parse(data);
                    isRet = (bool)dataJObject["ret"];
                    if (!isRet)
                        MB.Util.TraceEx.Write(dataJObject["retMsg"].ToString());
                }
                else
                {
                    mes = responseJObject["msg"].ToString();
                    MB.Util.TraceEx.Write(mes);
                }
            }
            catch (Exception ex)
            {
                success = false;
                mes = ex.Message;
                MB.Util.TraceEx.Write(ex.Message);
            }

            return success;
        }

        public List<JDGoodsInfo> GetJDGoods(int pageNo = 1, int pageSize = 20, int allcount = 1)
        {
            List<JDGoodsInfo> lstJDGoodsInfo = new List<JDGoodsInfo>();
            try
            {
                string action = "/pms/querySkuInfos";

                request_goods _request = new request_goods();
                _request.pageNo = pageNo.ToString();
                _request.pageSize = pageSize.ToString();
                string jd_param_json = JsonConvert.SerializeObject(_request);
                string response = GetJDAPI(action, jd_param_json);

                JObject responseJObject = JObject.Parse(response);
                //API调用结果
                bool success_response = (bool)responseJObject["success"];
                if (success_response)
                {
                    string data = responseJObject["data"].ToString();
                    JObject dataJObject = JObject.Parse(data);
                    bool success_data = (bool)dataJObject["success"];
                    if (success_data)
                    {
                        string result = dataJObject["result"].ToString();
                        JObject resultJObject = JObject.Parse(result);
                        string resultSku = resultJObject["result"].ToString();
                        dynamic lstSku = JsonConvert.DeserializeObject(resultSku);
                        foreach (JObject item in lstSku)
                        {
                            JDGoodsInfo _JDGoodsInfo = new JDGoodsInfo();
                            _JDGoodsInfo.skuId = (long)item["skuId"];
                            _JDGoodsInfo.outSkuId = item["outSkuId"].ToString();
                            lstJDGoodsInfo.Add(_JDGoodsInfo);
                        }
                        allcount = (int)resultJObject["count"];
                        if (pageNo * pageSize < allcount)
                        {
                            lstJDGoodsInfo.AddRange(GetJDGoods(pageNo + 1, pageSize, allcount));
                        }
                    }
                    else
                    {
                        MB.Util.TraceEx.Write(dataJObject["msg"].ToString());
                    }
                }
                else
                {
                    MB.Util.TraceEx.Write(responseJObject["msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
            }
            return lstJDGoodsInfo;
        }

        public string GetJDAPI(string action, string jd_param_json)
        {
            JDAPIConfig _JDAPIConfig = JDAPIConfig.Value;
            string format = _JDAPIConfig.format;
            string v = _JDAPIConfig.v;
            string token = _JDAPIConfig.token;
            string app_key = _JDAPIConfig.app_key;
            string app_secret = _JDAPIConfig.app_secret;
            string url = _JDAPIConfig.url + action;
            //string format = "json";
            //string v = "1.0";
            //string token = "6e216d76-6d6a-40e4-b8ba-572d1ef0ee16";
            //string app_key = "31a6a28967fd457690fe555303e5edea";
            //string app_secret = "247080e6eaf8468399f938e04b339dcd";

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("token", token);
            dic.Add("app_key", app_key);
            dic.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            dic.Add("format", format);
            dic.Add("v", v);
            dic.Add("jd_param_json", jd_param_json);

            string sign = GetMD5String(dic, app_secret).ToUpper();

            string response = new ClientChannel().Get(string.Format("{0}?v={7}&format={8}&app_key={1}&app_secret={2}&token={3}&jd_param_json={4}&sign={5}&timestamp={6}",
                    url, app_key, app_secret, token, dic["jd_param_json"], sign, dic["timestamp"], v, format));

            return response;
        }

        #region 请求类
        public class request_goods
        {
            public string pageNo { get; set; }
            public string pageSize { get; set; }
        }
        public class request_upload
        {
            public string stationNo { get; set; }
            public string skuId { get; set; }
            public string currentQty { get; set; }
        }
        #endregion

        public string GetMD5String(Dictionary<string, string> dic, string app_secret)
        {
            Object[] key_arr = dic.Keys.ToArray();
            Array.Sort(key_arr);
            StringBuilder sysStr = new StringBuilder();
            foreach (Object key in key_arr)
            {
                string val = dic[key.ToString()];
                sysStr.Append(key).Append(val);
            }
            StringBuilder resultStr = new StringBuilder();
            resultStr.Append(app_secret).Append(sysStr).Append(app_secret);
            return FormsAuthentication.HashPasswordForStoringInConfigFile(resultStr.ToString(), "MD5").ToUpper();
        }

    }
}
